package cn.com.panda;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.spec.ECField;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cn.com.panda.base.BaseActivity;
import cn.com.panda.bean.BtDevice;
import cn.com.panda.conf.Config;
import cn.com.panda.utils.ScreenUtils;
import cn.com.panda.utils.ToastUtils;
import cn.com.panda.view.dialog.DialogWithProgress;
import cn.com.panda.view.recycleview.Refrush_More_RecycleView;
import cn.com.panda.view.recycleview.recycleadapter.RecycleCommonAdapter;
import cn.com.panda.view.recycleview.recycleadapter.itemview.ViewHolder;

public class BlueToothActivity extends BaseActivity {

    private final String TAG = BlueToothActivity.this.getClass().getName();

    private final static int REQUEST_ENABLE_BT = 10001;

    private static BluetoothAdapter bluetoothAdapter;
    private static Set<BluetoothDevice> pairedDevices;
    private static String selfDeviceName;
    private static Refrush_More_RecycleView devicelist;
    private static RecycleCommonAdapter<BtDevice> adapter;
    private static List<BtDevice> list = new ArrayList<>();
    private static List<BtDevice> hadlist = new ArrayList<>();
    private ImageView closeimg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_tooth);

        if(!isAllowPermission(Manifest.permission.BLUETOOTH)){
            requestPermission(this,Manifest.permission.BLUETOOTH);
        }

        if(!isAllowPermission(Manifest.permission.ACCESS_FINE_LOCATION)){
            requestPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);
        }

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        selfDeviceName = getIntent().getExtras().getString("btdevice","");//通过登录传入的蓝牙设备名称
        devicelist = findViewById(R.id.devicelist);
        devicelist.initView(1,1, getResources().getColor(R.color.line));
        adapter = new RecycleCommonAdapter<BtDevice>(mContext,devicelist.getRecyclerView(),list,false,R.layout.bluetooth_item){

            @Override
            public void conver(ViewHolder viewHandler, BtDevice item, int position) {
                viewHandler.setText(R.id.devicename,item.getDeviceName());
                viewHandler.setText(R.id.deviceaddress,"蓝牙地址："+item.getDeviceMac());
            }
        };
        adapter.showFootView(false);
        devicelist.setRecycleCommonAdapter(adapter);
        devicelist.setEventListener(new Refrush_More_RecycleView.EventListener() {
            @Override
            public void onRefrushListener() {
                searchDevice();
            }

            @Override
            public void onMoreListener(int lastPosition) {

            }

            @Override
            public void onItemClick(View v, int position) {
                BtDevice bluetoothDevice = list.get(position);
                if(bluetoothDevice == null){
                    ToastUtils.showShort(mContext,"该设备无效");
                    return;
                }
                bluetoothAdapter.cancelDiscovery();//adapter为获取到的蓝牙适配器
                //连接设备---无蓝牙，暂时不发起链接
                try {
//                    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bluetoothDevice.getDeviceMac());
//                    ClientThread clientThread = new ClientThread(device);
//                    clientThread.start();

                    Bundle bundle = new Bundle();
                    bundle.putString("name",bluetoothDevice.getDeviceName());
                    bundle.putString("mac",bluetoothDevice.getDeviceMac());
                    BlueToothActivity.this.setResult(RESULT_OK);
                    toActivity(CameraActivity.class,bundle);

                    BlueToothActivity.this.finish();

                }catch (Exception e){
                    e.printStackTrace();
                    Log.e(TAG,e.getMessage());
                    ToastUtils.showLong(mContext,"设备无法连接，请进行蓝牙设置");
                }

            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });

        TextView description = findViewById(R.id.description);
        description.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到指南页面
                Bundle bundle = new Bundle();
                bundle.putString("url", Config.instructions);
                toActivity(WebViewActivity.class,bundle);
            }
        });

        // 发现蓝牙设备.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);

        Button sysbluetooth = findViewById(R.id.sysbluetooth);
        sysbluetooth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        TextView tosysbt = findViewById(R.id.tosysbt);
        tosysbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        closeimg = findViewById(R.id.closeimg);
        closeimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BlueToothActivity.this.finish();
            }
        });
    }

    private void searchDevice(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //搜索蓝牙设备
                if (bluetoothAdapter.isDiscovering()) {
                    //判断蓝牙是否正在扫描，如果是调用取消扫描方法；如果不是，则开始扫描
                    Log.e("search bluetooth","cancel");
                    bluetoothAdapter.cancelDiscovery();
                    searchDevice();
                } else {
                    list.clear();
                    boolean isrunning = bluetoothAdapter.startDiscovery();
                    Log.e("search bluetooth",isrunning+"");
                }

            }
        }).start();
    }

    class ClientThread extends Thread {

        private BluetoothDevice device;

        public ClientThread(BluetoothDevice device){
            this.device = device;
        }

        public void run() {
            try {
                final BluetoothSocket socket = (BluetoothSocket) device.getClass().getDeclaredMethod("createRfcommSocket", new Class[]{int.class}).invoke(device, 1);
                try {
                    socket.connect();//连接
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }

    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                devicelist.setVisibility(View.VISIBLE);
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                BtDevice btDevice = new BtDevice();
                btDevice.setDeviceName(deviceName);
                btDevice.setDeviceMac(deviceHardwareAddress);
                list.add(btDevice);
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void onDestroy() {
        if(receiver != null){
            unregisterReceiver(receiver);
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }

    private void initView(){
        if(!isAllowPermission(Manifest.permission.BLUETOOTH)) {
            ToastUtils.showLong(mContext,"未开启蓝牙权限，无法识别蓝牙设备");
            return;
        }
        //获取当前连接蓝牙设备
        if (bluetoothAdapter == null) {
            ToastUtils.showLong(mContext,"您的设备不支持蓝牙功能");
            return;
        }

        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }else{
//            getBondedDevices();
            searchDevice();
        }
    }

    @Override
    protected void checkPermissionResult(String[] permissions, int[] grantResults) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_ENABLE_BT){
            if(resultCode == RESULT_OK){
//                getBondedDevices();
                searchDevice();
            }
        }
    }

    /**
     * 获取已经连接成功的设备
     */
    private void getBondedDevices(){
        if(bluetoothAdapter == null){
            displayBluetooth(false);
            return;
        }
        hadlist.clear();
        pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices!=null && pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                BtDevice btDevice = new BtDevice();
                btDevice.setDeviceMac(deviceHardwareAddress);
                btDevice.setDeviceName(deviceName);
                hadlist.add(btDevice);
            }
        }

        if(hadlist.size() > 0) {
            devicelist.setVisibility(View.VISIBLE);
            list.addAll(hadlist);
            adapter.notifyDataSetChanged();
        }
        displayBluetooth(list.size() > 0);
    }

    private void displayBluetooth(boolean isshow){
        RelativeLayout nobluetoothlayout = findViewById(R.id.nobluetoothlayout);
        nobluetoothlayout.setVisibility(isshow?View.GONE:View.VISIBLE);
        FrameLayout bluetoothlayout = findViewById(R.id.bluetoothlayout);
        bluetoothlayout.setVisibility(isshow?View.VISIBLE:View.GONE);
    }
}